/**
 * 
 */
package com.edoomath.api.web.controller.course;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.CollectionUtils;
import com.edoomath.api.servcice.CourseItemService;
import com.edoomath.api.servcice.UserCourseItemService;
import com.edoomath.api.servcice.UserService;
import com.edoomath.entity.course.Course;
import com.edoomath.entity.course.CourseItem;
import com.edoomath.entity.course.CourseItemStat;
import com.edoomath.entity.course.CourseMaterail;
import com.edoomath.entity.course.CourseMaterialCategory;
import com.edoomath.entity.course.CourseText;
import com.edoomath.entity.user.User;
import com.edoomath.entity.usercourse.UserCourseMaterialCategory;

/**
 * @author downpour
 *        
 */
@Controller
@RequestMapping("/course-items")
public class CourseItemController {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseItemController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CourseItemService courseItemService;
    
    @Autowired
    private UserCourseItemService userCourseItemService;
    
    /**
     * 
     * @param id
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult loadCourseItem(@PathVariable(value = "id") Long id,
    							     @RequestParam(value = "unionid") String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            // 1. course-item information
            CourseItem courseItem = courseItemService.loadCourseItem(id);
            Course course = courseItem.getCourse();
            
            CourseItemStat courseItemStat = courseItemService.loadCourseItemStat(courseItem);
            
            return httpResult.success().data("courseItem", courseItem)
                                       .data("course", course)
                                       .data("courseItemStat", courseItemStat)
                                       .message("获取课程信息成功");
            
        } catch (Exception e) {
            logger.error("load course item failed with error", e);
            return httpResult.fail("500").message("获取课程信息失败");
        }
        
    }
    
    /**
     * 
     * @param itemid
     * @param types
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{id}/materials", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult listMaterials(@PathVariable(value = "id") Long itemid,
    								@RequestParam(value = "type") List<String> types,
    								@RequestParam(value = "unionid") String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            // 1. course-item information
            CourseItem courseItem = courseItemService.loadCourseItem(itemid);
            List<CourseMaterail> materials = courseItemService.listCourseMaterial(courseItem, types);
            
            Map<String, List<CourseMaterail>> result = CollectionUtils.constructMapValues(materials, "type");
            
            // 2. TODO get progress according to the user
            
            return httpResult.success().data("courseMaterails", result)
                                       .message("获取资料信息成功");
            
        } catch (Exception e) {
            logger.error("load course item failed with error", e);
            return httpResult.fail("500").message("获取资料信息失败");
        }
        
    }
    
    /**
     * 
     * @param itemid
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{id}/backup-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult listBackupCategories(@PathVariable(value = "id") Long itemid,
    								@RequestParam(value = "unionid") String unionid) {
    	HttpResult httpResult = new HttpResult();
    	
    	try {
    		
    		User user = userService.load(unionid);
        	if(user.isChildren() && StringUtils.isNotBlank(user.getMobile())) {
        		user = userService.getParent(user);
        		unionid = user.getUnionid();
        	}
    		
    		CourseItem courseItem = courseItemService.loadCourseItem(itemid);
            List<CourseMaterialCategory> categories = courseItemService.listCourseMaterialCategory(courseItem);
    		
            List<UserCourseMaterialCategory> userCourseMaterialCategories = userCourseItemService.listUserCourseMaterialCategory(unionid);
            Map<String, UserCourseMaterialCategory> userCourseMaterialCategoriesMap = CollectionUtils.constructMapValue(userCourseMaterialCategories, "category.id");
            
            return httpResult.success().data("categories", categories)
            						   .data("userCategories", userCourseMaterialCategoriesMap)
                    				   .message("获取资料信息成功");
    		
    	} catch (Exception e) {
    		logger.error("load course item failed with error", e);
            return httpResult.fail("500").message("获取题库分类信息失败");
    	}
    }
    
    /**
     * 
     * @param itemid
     * @param categoryId
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{id}/{categoryId}/materials", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult listCategoryMaterial(@PathVariable(value = "id") Long itemid,
    									   @PathVariable(value = "categoryId") Long categoryId,
    									   @RequestParam(value = "unionid") String unionid) {
    	
    	HttpResult httpResult = new HttpResult();
    	
    	try {
    		
    		CourseMaterialCategory category = courseItemService.loadCourseMaterialCategory(categoryId);
    		
    		List<CourseMaterail> materails = courseItemService.listCourseMaterial(category);
    		Map<String, List<CourseMaterail>> result = CollectionUtils.constructMapValues(materails, "type");
    		
            return httpResult.success().data("materails", result)
                    				   .message("获取资料信息成功");
    		
    	} catch (Exception e) {
    		logger.error("load course item failed with error", e);
            return httpResult.fail("500").message("获取题库分类信息失败");
    	}
    }
    
    /**
     * 
     * @param itemid
     * @param categoryId
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{id}/{categoryId}/zip-material", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult loadCategoryZip(@PathVariable(value = "id") Long itemid,
    									   @PathVariable(value = "categoryId") Long categoryId,
    									   @RequestParam(value = "unionid") String unionid) {
    	
    	HttpResult httpResult = new HttpResult();
    	
    	try {
    		
    		CourseMaterialCategory category = courseItemService.loadCourseMaterialCategory(categoryId);
    		
    		CourseMaterail materail = courseItemService.loadCourseMaterial(category);
    		
            return httpResult.success().data("materail", materail)
                    				   .message("获取资料信息成功");
    		
    	} catch (Exception e) {
    		logger.error("load course item failed with error", e);
            return httpResult.fail("500").message("获取题库分类信息失败");
    	}
    }
    
    /**
     * 
     * @param courseItemId
     * @param courseTextType
     * @return
     */
    @RequestMapping(value = "/{courseItemId}/course-texts/{courseTextType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult loadCourseText(@PathVariable(value = "courseItemId") Long courseItemId, @PathVariable(value = "courseTextType") String courseTextType) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
        	CourseItem courseItem = courseItemService.loadCourseItem(courseItemId);
        	
        	List<CourseText> courseTexts = courseItemService.listCourseText(courseItem, courseTextType);
            
            return httpResult.success()
            				 .data("courseTexts", courseTexts)
            				 .message("获取课程信息成功");
            
        } catch (Exception e) {
            logger.error("load course item failed with error", e);
            return httpResult.fail("500").message("获取课程信息失败");
        }
        
    }
    
}
